$(function(){
    loadStudentList();
});

function loadStudentList(){
    $.ajax({
        url:"/api/student/list"
    }).done(function(data) {
        let html = "";
        data.forEach((element,index) => {
            html += "<tr>";
            html += "<td>"+ element.id +"</td>";
            html += "<td>"+ element.name +"</td>";
            html += "<td>"+ element.sex +"</td>";
            html += "<td>"+ element.age +"</td>";
            html += "<td>"+ element.sno +"</td>";
            html += "<td><a href='#' onclick='showStudentDlg("+element.id+")'>编辑</a> &nbsp;&nbsp;<a href='#' onclick='deleteById("+element.id+")'>删除</a></td>";
            html += "</tr>";
        });
        $("#studentTb").html(html);
    });
}

let layerIndex;
let isEditMode = false;

function showStudentDlg(id) {
    // 重置表单
    $('#studForm')[0].reset();

    let title = "新增教师";
    isEditMode = false;

    // 显示或隐藏ID字段（假设您有一个id字段）
    $("#formid").css("display", "none");

    if (id) {
        // 编辑模式
        title = "编辑教师";
        isEditMode = true;
        $("#formid").css("display", "block");

        // 读取学生信息并赋值
        $.ajax({
            url:"/api/student/"+id,
            method:"GET"
        }).done(result=>{
            console.log(result);
            // 修正了选择器语法错误
            $.each(result, function(key, value) {
                var field = $('#studForm [name="'+key+'"]'); // 移除了多余的空格
                if (field.is(':radio')) {
                    field.filter('[value="'+value+'"]').prop('checked', true);
                } else if (field.is(':checkbox')) {
                    field.prop('checked', value === "yes" || value === true);
                } else {
                    field.val(value);
                }
            });
        }).fail(error=>{
            console.error("加载教师信息失败:", error);
            layer.msg("加载教师信息失败", {icon: 2});
        });
    }

    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ["520px", "auto"],
        content: $("#studForm")
    });
}

layui.use(function(){
    layui.form.on("submit(stud-dlg)", function(data) {
        event.preventDefault();
        commitStuDlg();
    });
});

function commitStuDlg(){
    let formData = $("#studForm").serialize();
    let url = isEditMode ? "/api/student/update" : "/api/student/add";
    let method = isEditMode ? "PUT" : "POST";

    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");

    $.ajax({
        url: url,
        method: method,
        data: formData
    }).done(result=>{
        console.log(result);
        if(result.id || result.success){
            loadStudentList();
            if(layerIndex) layer.close(layerIndex);
            layer.msg(isEditMode ? "更新成功" : "添加成功", {icon: 1});
        } else {
            layer.msg(result.message || "操作失败", {icon: 2});
        }
    }).fail((jqXHR, textStatus, errorThrown) => {
        console.error("Request failed: " + textStatus + " - " + errorThrown);
        layer.msg("操作失败: " + (jqXHR.responseJSON && jqXHR.responseJSON.message || "服务器错误"), {icon: 2});
    }).always(() => {
        $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
    });
}

function deleteById(id) {
    layer.confirm('你真的要删除吗？一旦删除，不可恢复！', {icon: 3, title: '提示'}, function(index) {
        $.ajax({
            url: "/api/student/delete/" + id,
            method: "DELETE",
            success: function(res) {
                layer.msg("删除成功！");
                loadStudentList(); // 正确地调用函数
            },
            error: function() {
                layer.msg("删除失败，请稍后再试！");
            },
            complete: function() {
                layer.close(index); // 关闭当前确认框
            }
        });
    });
}

$(function () {
    $('#searchBtn').on('click', function () {
        let keyword = $('#searchInput').val().trim();

        if (!keyword) {
            layer.msg("请输入姓名或ID！");
            return;
        }

        $.ajax({
            url: "/api/student/list",
            method: "GET"
        }).done(function (data) {
            let filtered = data.filter(item =>
                item.name.includes(keyword) || item.id.toString().includes(keyword)
            );

            if (filtered.length === 0) {
                layer.msg("没有找到匹配的数据");
                return;
            }

            let html = "";
            filtered.forEach(item => {
                html += "<tr>";
                html += "<td>" + item.id + "</td>";
                html += "<td>" + item.name + "</td>";
                html += "<td>" + (item.sex == 1 ? "男" : "女") + "</td>";
                html += "<td>" + item.age + "</td>";
                html += "<td>" + item.sno + "</td>";
                html += "<td>";
                html += "<a href='#' onclick='showStudentDlg(" + item.id + ")'>编辑</a> &nbsp;&nbsp;";
                html += "<a href='#' onclick='deleteById(" + item.id + ")'>删除</a>";
                html += "</td>";

                html += "</tr>";
            });

            $("#searchResultBody").html(html);

            layer.open({
                type: 1,
                title: "搜索结果",
                area: ["700px", "auto"],
                content: $("#searchResultDialog"),
                shadeClose: true,
                end: function () {
                    $("#searchResultBody").empty();
                }
            });
        });
    });
});
















